<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card class="box-card">
          <el-input v-model="orgTreefilterText" :placeholder="$t('common.filter')" />
          <el-tree
            ref="orgTree"
            class="filter-tree"
            :highlight-current="true"
            :expand-on-click-node="false"
            :data="orgDate"
            :props="defaultProps"
            :current-node-key="orgTreeId"
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleOrgTreeClick"
          />
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card">
          <div class="filter-container">
            <el-input
              v-model="queryForm.name"
              :placeholder="$t('user.column.name.placeholder.query')"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="handleFilter"
            />
            <el-button
              v-waves
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >{{ $t('common.action.search') }}</el-button>
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-plus"
              @click="handleCreate"
            >{{ $t('common.action.add') }}</el-button>
            <el-checkbox
              v-model="isShowNoOrgUser"
              style="margin-left:15px;"
              class="filter-item"
              @change="apiPageUser()"
            >{{ $t('user.query.isShowNoOrgUser') }}</el-checkbox>
            <!-- <el-button
              v-waves
              :loading="downloadOrImprotLoading"
              class="filter-item"
              type="primary"
              icon="el-icon-upload2"
              @click="handleDownload"
            >{{ $t('common.action.export') }}</el-button>
            <el-button
              v-waves
              :loading="downloadOrImprotLoading"
              class="filter-item"
              type="primary"
              icon="el-icon-download"
              @click="handleImport"
            >{{ $t('common.action.import') }}</el-button>-->
          </div>
          <el-table :data="tableData" border fit highlight-current-row>
            <el-table-column prop="name" :label="$t('user.column.name.name')" />
            <el-table-column prop="organizationName" :label="$t('user.column.organization.name')" />
            <el-table-column prop="account" :label="$t('user.column.account.name')" />

            <el-table-column :label="$t('user.column.role.name')" />
            <el-table-column :label="$t('common.options')">
              <template slot-scope="{row}">
                <el-button
                  v-if="row.isSupperAdmin===0"
                  size="mini"
                  @click="handleEdit(row)"
                >{{ $t('common.action.edit') }}</el-button>

                <el-button
                  v-if="row.isSupperAdmin===0"
                  size="mini"
                  type="danger"
                  @click="handleDelete(row)"
                >{{ $t('common.action.delete') }}</el-button>

                <el-button
                  v-if="row.isSupperAdmin===0"
                  size="mini"
                  type="primary"
                  @click="handleSetRole(row)"
                >{{ $t('user.action.setRole') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="queryPage.total>0"
            :total="queryPage.total"
            :page.sync="queryPage.current"
            :limit.sync="queryPage.pageSize"
            @pagination="apiPageUser"
          />

          <el-dialog
            :title="$t('user.diglogTitle.setRoleTitle')"
            :visible.sync="dialogSetRoleVisible"
          >
            <el-checkbox-group v-model="roleValues">
              <el-checkbox v-for="role in roleArray" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
            </el-checkbox-group>

            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogSetRoleVisible = false">{{ $t('common.action.close') }}</el-button>
              <el-button type="primary" @click="saveUserRole()">{{ $t('common.action.confirm') }}</el-button>
            </div>
          </el-dialog>

          <el-dialog :title="diglogTitleMap[dialogTitle]" :visible.sync="dialogEditFormVisible">
            <el-form
              ref="editForm"
              :rules="dialogTitle==='add'?addRules:editRules"
              :model="editForm"
              label-position="left"
              label-width="80px"
            >
              <el-form-item :label="$t('user.column.name.name')" prop="name">
                <el-input
                  v-model="editForm.name"
                  :placeholder="$t('user.column.name.placeholder.edit')"
                />
              </el-form-item>
              <el-form-item :label="$t('user.column.account.name')" prop="account">
                <el-input
                  v-model="editForm.account"
                  :placeholder="$t('user.column.account.placeholder.edit')"
                />
              </el-form-item>
              <el-form-item
                v-if="dialogTitle==='add'"
                :label="$t('user.column.password.name')"
                prop="password"
              >
                <el-input
                  v-model="editForm.password"
                  :placeholder="$t('user.column.password.placeholder.edit')"
                />
              </el-form-item>
              <el-form-item :label="$t('user.column.organization.name')" prop="organizationId">
                <select-tree
                  v-model="editForm.organizationId"
                  :options="orgDate"
                  :props="defaultProps"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogEditFormVisible = false">{{ $t('common.action.close') }}</el-button>
              <el-button
                type="primary"
                @click="dialogTitle==='add'?apiAddUser():apiModifyUser()"
              >{{ $t('common.action.confirm') }}</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { pageUser, addUser, deleteUser, detailUser, modifyUser, getUserRole, saveUserRole } from '@/api/user'
import { listRole } from '@/api/system/role'

import { fetchList } from '@/api/system/organization'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import SelectTree from '@/components/SelectTree.vue'

export default {
  directives: { waves },
  components: { Pagination, SelectTree },
  data() {
    return {
      orgDate: [],
      orgTreeId: null,
      defaultProps: {
        parent: 'parentId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'name', // 标签显示
        children: 'children' // 子级
      },
      orgTreefilterText: undefined,

      queryForm: {
        searchKey: name
      },
      queryPage: {
        current: 1,
        pageSize: 20,
        total: 0
      },

      isShowNoOrgUser: false,
      tableData: [],

      editForm: {
        id: undefined,
        name: undefined,
        account: undefined,
        organizationId: null,
        password: null
      },
      editRules: {

      },
      addRules: {
        name: [{ required: true, message: this.$t('validate.notNull'), trigger: 'blur' }],
        account: [{ required: true, message: this.$t('validate.notNull'), trigger: 'blur' }],
        organizationId: [{ required: true, message: this.$t('validate.notNull'), trigger: 'blur' }],
        password: [{ required: true, message: this.$t('validate.notNull'), trigger: 'blur' }]
      },

      dialogEditFormVisible: false,
      dialogTitle: '',
      diglogTitleMap: {
        add: this.$t('user.diglogTitle.add'),
        edit: this.$t('user.diglogTitle.edit')
      },

      dialogSetRoleVisible: false,
      roleArray: [],
      roleValues: [],
      setRoleUserId: undefined
    }
  },
  watch: {
    orgTreefilterText(val) {
      this.$refs.orgTree.filter(val)
    }
  },
  created() {
    fetchList().then(response => {
      this.orgDate = response.data
    })
    this.apiPageUser()
    this.apiListRole()
  },
  methods: {

    apiListRole() {
      listRole().then(response => {
        this.roleArray = response.data
      })
    },

    // 树形组织结构
    handleOrgTreeClick(data) {
      this.orgTreeId = data.id
      this.$nextTick(() => {
        this.$refs.orgTree.setCurrentKey(data.id) // treeBox 元素的ref   value 绑定的node-key
      })
      this.apiPageUser()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    // 用户操作
    apiPageUser() {
      pageUser(this.queryPage, this.queryForm, this.orgTreeId, this.isShowNoOrgUser).then(response => {
        this.tableData = response.data.items
        this.queryPage.total = Number(response.data.total)
      })
    },
    apiAddUser() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          addUser(this.editForm).then(response => {
            this.apiPageUser()
            this.dialogEditFormVisible = false
            this.$notify({
              title: this.$t('notify.success'),
              message: this.$t('common.options_success'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    apiModifyUser() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          modifyUser(this.editForm).then(response => {
            this.apiPageUser()
            this.dialogEditFormVisible = false
            this.$notify({
              title: this.$t('notify.success'),
              message: this.$t('common.options_success'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    apiDeleteUser(id) {
      deleteUser(id).then(response => {
        this.apiPageUser()
        this.$notify({
          title: this.$t('notify.success'),
          message: this.$t('common.options_success'),
          type: 'success',
          duration: 2000
        })
      })
    },
    apiDetailUser(id) {
      detailUser(id).then(response => {
        this.editForm = response.data
      })
    },

    handleFilter() {
      this.apiPageUser()
    },
    handleCreate() {
      this.dialogTitle = 'add'
      this.editForm = {
        organizationId: this.orgTreeId
      }
      this.dialogEditFormVisible = true
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },

    handleDelete(row) {
      this.$confirm(this.$t('common.confirm_delete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.action.confirm'),
        cancelButtonText: this.$t('common.action.cancel'),
        type: 'warning'
      }).then(() => {
        this.apiDeleteUser(row.id)
      })
    },
    handleEdit(row) {
      this.dialogTitle = 'edit'
      this.apiDetailUser(row.id)
      this.dialogEditFormVisible = true
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },
    handleSetRole(row) {
      this.setRoleUserId = row.id
      this.dialogSetRoleVisible = true
      getUserRole(row.id).then(response => {
        this.roleValues = response.data
      })
    },

    saveUserRole() {
      saveUserRole(this.setRoleUserId, this.roleValues).then(response => {
        this.dialogSetRoleVisible = false
        this.$notify({
          title: this.$t('notify.success'),
          message: this.$t('common.options_success'),
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDownload() { },
    handleImport() { }

  }
}
</script>
